// UserProfileViewModel.kt
package com.example.nutritionmanager.viewModels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.nutritionmanager.api.UserService
import com.example.nutritionmanager.bodys.responseBodys.UserProfileResponse
import com.example.nutritionmanager.data.UserProfileDataStore
import com.example.nutritionmanager.UserProfile
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject

// 定义用户资料状态的密封类
sealed class UserProfileState {
    object Idle : UserProfileState()
    object Loading : UserProfileState()
    data class Success(val userProfile: UserProfile) : UserProfileState()
    data class Error(val error: String) : UserProfileState()
}

@HiltViewModel
class UserProfileViewModel @Inject constructor(
    private val userService: UserService,
    private val userProfileDataStore: UserProfileDataStore
) : ViewModel() {

    // 状态流：管理用户资料状态
    private val _userProfileState = MutableStateFlow<UserProfileState>(UserProfileState.Idle)
    val userProfileState: StateFlow<UserProfileState> = _userProfileState.asStateFlow()

    // 监听本地存储的用户资料
    private val localUserProfileFlow = userProfileDataStore.getUserProfile
        .map { response ->
            response?.let {
                UserProfile(
                    username = it.username,
                    age = it.age.toString(),
                    gender = if (it.gender == 1) "男" else if (it.gender == 2) "女" else "未定义",
                    height = it.height.toString(),
                    weight = it.weight.toString(),
                    registerDate = it.registerDate,
                    targetCalories = it.targetCalories.toString(),
                    period = if (it.period == 1) "减脂期" else if (it.period == 2) "增肌期" else "保持期"
                )
            }
        }

    // 合并网络和本地数据
    init {
        viewModelScope.launch {
            localUserProfileFlow.collect { localProfile ->
                localProfile?.let {
                    _userProfileState.value = UserProfileState.Success(it)
                }
            }
        }
    }

    // 获取用户资料从网络并保存到本地
    fun fetchUserProfile() {
        viewModelScope.launch {
            _userProfileState.value = UserProfileState.Loading
            try {
                val response = userService.getUserProfile()
                if (response.isSuccessful) {
                    response.body()?.let { userProfileResponse ->
                        // 保存到本地 DataStore
                        userProfileDataStore.saveUserProfile(userProfileResponse)
                        // 更新 UI 状态
                        val userProfile = UserProfile(
                            username = userProfileResponse.username,
                            age = userProfileResponse.age.toString(),
                            gender = if (userProfileResponse.gender == 1) "男" else if (userProfileResponse.gender == 2) "女" else "未定义",
                            height = userProfileResponse.height.toString(),
                            weight = userProfileResponse.weight.toString(),
                            registerDate = userProfileResponse.registerDate, // 根据需要格式化
                            targetCalories = userProfileResponse.targetCalories.toString(),
                            period = if (userProfileResponse.period == 1) "减脂期" else if (userProfileResponse.period == 2) "增肌期" else "保持期"
                        )
                        _userProfileState.value = UserProfileState.Success(userProfile)
                    } ?: run {
                        _userProfileState.value = UserProfileState.Error("空的用户资料")
                    }
                } else {
                    _userProfileState.value = UserProfileState.Error("获取用户资料失败: ${response.message()}")
                }
            } catch (e: Exception) {
                _userProfileState.value = UserProfileState.Error("发生错误: ${e.localizedMessage}")
            }
        }
    }

    // 更新用户资料并保存到本地（根据具体需求实现）
    fun updateUserProfile(updatedProfile: UserProfile) {
        viewModelScope.launch {
            // 示例：假设有一个 API 调用来更新用户资料
            /*
            try {
                val response = userService.updateUserProfile(updatedProfile.toRequestBody())
                if (response.isSuccessful) {
                    // 更新本地 DataStore
                    userProfileDataStore.saveUserProfile(response.body()!!)
                    _userProfileState.value = UserProfileState.Success(updatedProfile)
                } else {
                    _userProfileState.value = UserProfileState.Error("更新资料失败")
                }
            } catch (e: Exception) {
                _userProfileState.value = UserProfileState.Error("发生错误: ${e.localizedMessage}")
            }
            */
            // 这里只是简单更新本地状态
            userProfileDataStore.saveUserProfile(
                UserProfileResponse(
                    userId = 1L, // 实际使用中应为当前用户 ID
                    username = updatedProfile.username,
                    gender = if (updatedProfile.gender == "男") 1 else 0,
                    age = 25, // 根据实际情况填充
                    weight = updatedProfile.weight.toDouble(),
                    height = updatedProfile.height.toDouble(),
                    period = 1, // 根据实际情况填充
                    targetCalories = 2000, // 根据实际情况填充
                    registerDate = updatedProfile.registerDate
                )
            )
            _userProfileState.value = UserProfileState.Success(updatedProfile)
        }
    }

    // 清除用户资料（例如登出）
    fun clearUserProfile() {
        viewModelScope.launch {
            userProfileDataStore.clearUserProfile()
            _userProfileState.value = UserProfileState.Idle
        }
    }
}
